<!--
 * @Descripttion: 登录页面组件
 * @Author: congz
 * @Date: 2020-06-11 11:08:34
 * @LastEditors: congz
 * @LastEditTime: 2020-08-19 10:14:30
-->

<template>
  <div class='login'>
    <div style='text-align: center;margin-top: 20px'>
 <span style='color: #000000;
                font-size: 55px;
                font-weight: 800;
                font-family: 华光行草_CNKI;'>
                北林信息学院购物平台
            </span>
    </div>
    <el-dialog
      :modal-append-to-body='false'
      title='详细注册'
      :close-on-click-modal='false'
      :visible.sync='registerDialogVisible'
      width='30%'
      center>
      <el-form :model='detailregister' :rules='rules' ref='detailregister' label-width='80px'>
        <el-form-item label='用户名' label-width='120px' prop='username' placeholder='用户名'>
          <el-input prefix-icon='el-icon-lock' v-model='detailregister.username' clearable
                    style='width: 80%'></el-input>
        </el-form-item>
        <el-form-item label='密码' label-width='120px' prop='password' placeholder='密码'>
          <el-input prefix-icon='el-icon-lock' v-model='detailregister.password' autocomplete='off'
                    style='width: 80%' show-password></el-input>
        </el-form-item>
        <el-form-item label='确认密码' label-width='120px' prop='newpwdConfirm' placeholder='确认密码'>
          <el-input prefix-icon='el-icon-lock' v-model='pwdtwice' autocomplete='off' style='width: 80%'
                    show-password></el-input>
        </el-form-item>
        <el-form-item label='邮箱' label-width='120px' prop='email' placeholder='请输入您的邮箱'>
          <el-input prefix-icon='el-icon-position' v-model='detailregister.email' autocomplete='off'
                    style='width: 80%'></el-input>
        </el-form-item>
      </el-form>
      <div slot='footer' class='dialog-footer'>
        <el-button @click="registering('detailregister')" type='danger'>提 交</el-button>
      </div>
    </el-dialog>
    <el-dialog
      :modal-append-to-body='false'
      title='找回密码'
      :close-on-click-modal='false'
      :visible.sync='centerDialogVisible'
      width='30%'
      center>
      <el-form :model='findback' :rules='rules' ref='findback' label-width='80px'>
        <el-form-item label='邮箱' label-width='120px' prop='email' placeholder='请输入您的邮箱以找回密码'>
          <el-input prefix-icon='el-icon-position' v-model='findback.email' autocomplete='off'
                    style='width: 80%'></el-input>
        </el-form-item>
        <el-form-item label='新密码' label-width='120px' prop='newpwd' placeholder='新密码'>
          <el-input prefix-icon='el-icon-lock' v-model='findback.newpwd' autocomplete='off' style='width: 80%'
                    show-password></el-input>
        </el-form-item>
        <el-form-item label='确认密码' label-width='120px' prop='newpwdConfirm' placeholder='确认密码'>
          <el-input prefix-icon='el-icon-lock' v-model='findback.newpwdConfirm' autocomplete='off'
                    style='width: 80%' show-password></el-input>
        </el-form-item>
        <el-form-item label='验证码' label-width='120px' prop='testcode'>
          <el-input prefix-icon='el-icon-key' v-model='findback.testcode' autocomplete='off' style='width: 80%'
                    maxlength='6'>
            <el-button slot='append' type='primary' @click="sendEmailCode('findback')" :disabled='disabled'>{{ msg }}<i
              class='el-icon-upload el-icon--right' style='width: 40%'></i></el-button>
          </el-input>
        </el-form-item>

      </el-form>
      <div slot='footer' class='dialog-footer'>
        <el-button @click="modifyCode('findback')" type='danger'>提 交</el-button>
      </div>
    </el-dialog>
    <el-card class='box-card'>
      <div class='tabs'>
        <ul>
          <li v-for='(v,i) in tabs' :key='i' @click='identity=i'
              :class="identity===i?'selected':''">
            {{ v }}
          </li>
        </ul>
      </div>
      <div class='logintext'>
        <h2>Welcome</h2>
      </div>
      <div class='formdata'>
        <el-form ref='form' :model='form' :rules='rules'>
          <el-form-item prop='username'>
            <el-input
              v-model='form.username'
              clearable
              placeholder='请输入账号'
            ></el-input>
          </el-form-item>
          <el-form-item prop='password'>
            <el-input
              v-model='form.password'
              clearable
              placeholder='请输入密码'
              show-password
            ></el-input>
          </el-form-item>
        </el-form>

      </div>
      <div class='tool'>
        <div>
          <el-checkbox v-model='checked' @change='remenber'>记住密码
          </el-checkbox>
        </div>
        <div>
          <span class='shou' @click='forgetpas'>忘记密码？</span>
        </div>
      </div>
      <div class='butt'>
        <el-button type='primary' @click.native.prevent="login('form')"
                   style='background-color: #ff9040;border: #ff9040 '>登录
        </el-button
        >
        <el-button class='shou' @click='register'>注册</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
import { login, register, sendingcode, modify } from '@/api/users/login'
import { mapActions } from 'vuex'
const Base64 = require('js-base64').Base64

export default {
  name: 'Login',
  data() {
    let validateEmail = (rule, value, callback) => {
      let emailReg = /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
      if (value === '' || value === undefined || value == null) {
        console.log('邮箱' + value)
        return callback(new Error('此项不能为空'))
      }
      setTimeout(() => {
        if (emailReg.test(value)) {
          console.log(1111)
          callback()
        } else {
          console.log(222)
          callback(new Error('请输入正确的邮箱格式'))
        }
      }, 800)
    }
    let validateCode = (rule, value, callback) => {
      let emailReg = /^\d{6}$/
      if (value === '' || value === undefined || value == null) {
        return callback(new Error('此项不能为空'))
      }
      setTimeout(() => {
        if (emailReg.test(value)) {
          console.log(1111)
          callback()
        } else {
          console.log(222)
          callback(new Error('请输入6位数字验证码'))
        }
      }, 800)
    }
    return {
      form: {
        password: '',
        username: ''
      },
      identity: 0,
      tabs: ['买家用户', '卖家用户'],
      registerDialogVisible: false,
      checked: false,
      disabled: false,
      count: 60,
      centerDialogVisible: false,
      msg: '获取验证码',
      detailregister: {
        username: '',
        password: '',
        email: ''
      },
      findback: {},
      pwdtwice: '',
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { max: 10, message: '不能大于10个字符', trigger: 'blur' }
        ],
        testcode: [{ validator: validateCode, trigger: 'change' }],
        email: [{ validator: validateEmail, trigger: 'change' }],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { max: 16, message: '不能大于16个字符', trigger: 'blur' }
          // {min: 8, message: "不能小于8个字符", trigger: "blur"},
        ]
      }
    }
  },
  created() {
    // 在页面加载时从cookie获取登录信息
    let username = this.getCookie('username')
    let password = Base64.decode(this.getCookie('password'))
    console.log(username, password)
    // 如果存在赋值给表单，并且将记住密码勾选
    if (username) {
      this.form.username = username
      this.form.password = password
      console.log(this.form.username, this.form.password)
      this.checked = true
    }
  },
  mounted() {
    let username = this.getCookie('username')
    let password = Base64.decode(this.getCookie('password'))
    console.log(username, password)
    // 如果存在赋值给表单，并且将记住密码勾选
    if (username) {
      this.form.username = username
      this.form.password = password
      console.log(this.form.username, this.form.password)
      this.checked = true
    }
  },

  methods: {
    ...mapActions(['setUser']),
    getCookie: function(key) {
      if (document.cookie.length > 0) {
        let start = document.cookie.indexOf(key + '=')
        if (start !== -1) {
          start = start + key.length + 1
          var end = document.cookie.indexOf(';', start)
          if (end === -1) end = document.cookie.length
          return unescape(document.cookie.substring(start, end))
        }
      }
      return ''
    },
    // 保存cookie
    setCookie: function(cName, value, expiredays) {
      let exdate = new Date()
      exdate.setDate(exdate.getDate() + expiredays)
      document.cookie = cName + '=' + decodeURIComponent(value) +
        ((expiredays == null) ? '' : ';expires=' + exdate.toGMTString())
    },

    setUserInfo: function() {
      // 判断用户是否勾选记住密码，如果勾选，向cookie中储存登录信息，
      // 如果没有勾选，储存的信息为空
      if (this.checked) {
        this.setCookie('username', this.form.username)
        // base64加密密码
        let passWord = Base64.encode(this.form.password)
        this.setCookie('password', passWord)
      } else {
        this.setCookie('username', '')
        this.setCookie('password', '')
      }
    },
    login(form) {
      this.$refs[form].validate((valid) => {
        if (valid) {
          this.form['identity'] = this.identity
          login(this.form)
            .then((res) => {
              console.log(res)
              if (res.status === 200) {
                this.$message({
                  message: '登录成功啦',
                  type: 'success',
                  showClose: true
                })
                localStorage.setItem('user', JSON.stringify(res.data))
                this.setUserInfo()
                this.$refs[form].resetFields()
                this.setUser(res.data)
                console.log(res.data)
                if (this.identity === 0) {
                  this.$router.push({ path: '/' })
                } else {
                  this.$router.push({ path: '/SellViews/sellHome' })
                }
              } else {
                this.$message({
                  message: res.data,
                  type: 'error',
                  showClose: true
                })
              }
            })
            .catch(error => {
              console.log(error)
              this.notifyError('登录失败', error)
            })

        } else {
          return false
        }
      })
    },
    remenber(data) {
      this.checked = data
      if (this.checked) {
        localStorage.setItem('news', JSON.stringify(this.form))
      } else {
        localStorage.removeItem('news')
      }
    },
    sendEmailCode(formName) {
      this.$refs[formName].validateField('email', result => {
        if (!result) {
          // 按钮倒计时
          this.disabled = true
          this.msg = this.count-- + 's后重新获取'
          this.timer = setInterval(() => {
            this.msg = this.count-- + 's后重新获取'
            if (this.count < 0) {
              this.msg = '点击获取验证码'
              this.count = 60
              this.disabled = false
              clearInterval(this.timer)
            }
          }, 1000)
          this.getcode()
        } else {
          this.$message({
            message: '邮箱格式错误',
            type: 'warning'
          })
        }
      })
    },
    getcode() {
      console.log(this.findback.email)
      sendingcode(this.findback.email).then(res => {
        console.log(res)
        if (res.data === '发送成功') {
          console.log('email' + this.findback.email)
          this.$notify({
            title: '邮箱验证码已发送',
            message: '验证码有效时长5分钟, 失效请重新发送',
            type: 'success',
            duration: 10 * 1000
          })
        } else {
        }
      })
    },
    modifyCode(formName) {
      if (this.findback.newpwd !== this.findback.newpwdConfirm) {
        this.$message({
          message: '您输入的两次密码不一致',
          type: 'warning'
        })
        return
      }
      if (!this.findback.testcode) {
        this.$message({
          message: '验证码为空',
          type: 'error'
        })
        return
      }

      console.log(formName)
      this.$refs[formName].validateField('email', result => {
        if (!result) {
          this.findback['identity'] = this.identity
          console.log(this.findback)
          modify(this.findback).then(res => {
            console.log(res)
            if (res.data === '修改成功') {
              this.$message({
                message: '修改成功',
                type: 'success'
              })
              this.$refs[formName].resetFields()
              this.centerDialogVisible = false
            } else if (res.data === '该邮箱未注册') {
              this.$message({
                message: '该邮箱未注册',
                type: 'error'
              })
            } else if (res.data === '验证码错误') {
              this.$message({
                message: '验证码错误',
                type: 'error'
              })
            }
          })
        } else {
          this.$message({
            message: '邮箱格式错误',
            type: 'warning'
          })
        }
      })
    },
    forgetpas() {
      this.centerDialogVisible = true
    },
    register() {
      this.registerDialogVisible = true
    },
    registering(formName) {
      if (this.detailregister.username === '' || this.detailregister.username === undefined || this.detailregister.username == null) {
        this.$message({
          message: '注册用户名不能为空',
          type: 'warning'
        })
        return
      }
      if (this.detailregister.password === '' || this.detailregister.password === undefined || this.detailregister.password == null) {
        this.$message({
          message: '您第一次输入的密码不能为空!',
          type: 'warning'
        })
        return
      }
      if (this.pwdtwice === '' || this.pwdtwice === undefined || this.pwdtwice == null) {
        this.$message({
          message: '您第二次输入的密码不能为空!',
          type: 'warning'
        })
        return
      }
      if (this.detailregister.password !== this.pwdtwice) {
        this.$message({
          message: '您输入的两次密码不一致',
          type: 'warning'
        })
        return
      }

      this.$refs[formName].validateField('email', result => {
        if (!result) {
          this.detailregister['identity'] = this.identity
          register(this.detailregister).then(res => {
              console.log(res)
              if (res.status === 200) {
                if (res.data === '用户名已存在') {
                  this.$message({
                    message: '用户名已存在',
                    type: 'error'
                  })
                } else if (res.data === '该邮箱已被注册') {
                  this.$message({
                    message: '该邮箱已被注册',
                    type: 'error'
                  })
                } else {
                  this.$message({
                    message: '注册成功',
                    type: 'success'
                  })
                  this.$refs[formName].resetFields()
                  this.pwdtwice = ''
                  this.registerDialogVisible = false
                }
              }
            }
          )
        } else {
          this.$message({
            message: '请检查邮箱格式',
            type: 'warning'
          })
        }
      })
    }
  }
}
</script>


<style scoped>
@import '../assets/css/button.css';

.text {
  font-size: 14px;
}

.item {
  margin: 0 auto;
  width: 300px;
}

.clearfix {
  font-size: 20px;
  margin-bottom: 20px;
}

.box-card {
  margin: 0 auto;
  text-align: center;
  width: 400px;
  margin-bottom: 400px;
  border-radius: 10px;
}

.box-card .line {
  height: 30px;
  width: 300px;
  margin: 0 auto;
  border-bottom: 1px solid #c0c0c0;
}

/*其他账号登录*/
.box-card .logo {
  width: 300px;
  margin: 0 auto;
  height: 30px;
  display: flex;
  align-items: center;
}

.box-card .logo .logo-info {
  font-size: 14px;
  color: #757575;
}

.box-card .logo .logo-login {
  height: 15px;
  margin-left: 10px;
}

/*其他账号登录END*/
</style>
<style scoped>
.login {
  width: 100%;
  height: 100%;
  min-width: 1000px;
  background-size: 100% 100%;
  background-position: center center;
  line-height: 80%;
  margin-bottom: 210px;
}

.logintext {
  margin-top: 10px;
  margin-bottom: 35px;
  line-height: 50px;
  text-align: center;
  font-size: 30px;
  font-weight: bolder;
  color: #e88b51;
  text-shadow: 2px 2px 4px #000000;
}

.box-card {
  margin: 0 auto;
  text-align: center;
  width: 400px;
  margin-top: 100px;
  margin-bottom: 200px;
  border-radius: 10px;
  background-color: #ffffff;
}

.box-card .line {
  height: 30px;
  width: 300px;
  margin: 0 auto;
  border-bottom: 1px solid #c0c0c0;
}

.tabs ul {
  display: flex;
  height: 50px;
  align-items: center;
  border-bottom: 1px solid #dedede;
  font-size: 20px;
  cursor: pointer;
}

.selected {
  color: #ff9040;
  font-weight: 700;
  position: relative;
}

.selected::before {
  content: '';
  position: absolute;
  left: 0;
  bottom: -19px;
  width: 100%;
  border-bottom: 3px solid #ff9040;
}


.tabs ul li {
  width: 50%;
  text-align: center;
}

.tabs ul li:not(:last-child) {
  border-right: 2px solid #dedede;
}

.tool {
  display: flex;
  justify-content: space-between;
  color: #606266;
}

.butt {
  margin-top: 10px;
  text-align: center;
}

.shou {
  cursor: pointer;
  color: #606266;
}

</style>
